//! 姓名生成器模块
//! 
//! 使用智能算法生成真实的中文和英文姓名，而不是简单的枚举列表

use rand::Rng;

/// 中文姓氏字符集 - 常用作姓氏的汉字特征
const ZH_SURNAME_CHARS: &[char] = &[
    '王', '李', '张', '刘', '陈', '杨', '赵', '黄', '周', '吴',
    '徐', '孙', '胡', '朱', '高', '林', '何', '郭', '马', '罗',
    '梁', '宋', '郑', '谢', '韩', '唐', '冯', '于', '董', '萧',
    '程', '曹', '袁', '邓', '许', '傅', '沈', '曾', '彭', '吕',
    '苏', '卢', '蒋', '蔡', '贾', '丁', '魏', '薛', '叶', '阎'
];

/// 中文名字常用字 - 按寓意分类
const ZH_GIVEN_NAME_POSITIVE: &[char] = &[
    '伟', '强', '明', '华', '建', '文', '志', '勇', '军', '杰',
    '涛', '超', '辉', '鹏', '磊', '峰', '龙', '虎', '豪', '俊'
];

const ZH_GIVEN_NAME_VIRTUE: &[char] = &[
    '德', '仁', '义', '礼', '智', '信', '忠', '孝', '廉', '耻',
    '善', '美', '真', '诚', '正', '直', '清', '雅', '和', '谐'
];

const ZH_GIVEN_NAME_NATURE: &[char] = &[
    '山', '水', '林', '森', '海', '江', '河', '湖', '云', '雨',
    '雪', '风', '雷', '电', '日', '月', '星', '光', '火', '土'
];

const ZH_GIVEN_NAME_FEMALE: &[char] = &[
    '芳', '娜', '敏', '静', '丽', '艳', '娟', '秀', '美', '玲',
    '婷', '雯', '慧', '琳', '颖', '洁', '莉', '萍', '红', '燕'
];

/// 英文姓氏音节模式
const EN_SURNAME_PREFIXES: &[&str] = &[
    "Sm", "John", "Will", "Br", "Jon", "Garc", "Mill", "Dav",
    "Rodr", "Mart", "Hern", "Lop", "Gonz", "Wils", "And",
    "Thom", "Tayl", "Moor", "Jack", "Mart", "Per", "Thomp",
    "Wh", "Harr", "Sanch", "Cl", "Ram", "Lew", "Rob"
];

const EN_SURNAME_SUFFIXES: &[&str] = &[
    "ith", "son", "iams", "own", "es", "ia", "er", "is",
    "iguez", "inez", "andez", "ez", "alez", "on", "erson",
    "as", "or", "e", "son", "in", "ee", "ez", "son",
    "ite", "is", "ez", "ark", "irez", "is", "inson"
];

/// 英文名字音节模式
const EN_GIVEN_NAME_PREFIXES: &[&str] = &[
    "Jam", "Rob", "Joh", "Mich", "Dav", "Will", "Rich", "Thom",
    "Chr", "Char", "Dan", "Matt", "Ant", "Mar", "Don",
    "Stev", "Pau", "And", "Josh", "Ken", "Kev", "Br", "Geo",
    "Tim", "Ron", "Jas", "Edw", "Jeff", "Ry", "Jac", "Gar"
];

const EN_GIVEN_NAME_SUFFIXES: &[&str] = &[
    "es", "ert", "n", "ael", "id", "iam", "ard", "as",
    "istopher", "les", "iel", "hew", "hony", "k", "ald",
    "en", "l", "rew", "ua", "neth", "in", "ian", "rge",
    "othy", "ald", "on", "ard", "rey", "an", "ob", "y"
];

/// 生成中文全名
pub fn zh_cn_fullname() -> String {
    let surname = zh_cn_surname();
    let given_name = zh_cn_given_name();
    format!("{}{}", surname, given_name)
}

/// 生成中文姓氏
/// 使用智能算法：70%概率使用常见姓氏，30%概率生成稀有姓氏
pub fn zh_cn_surname() -> String {
    let mut rng = rand::thread_rng();
    
    if rng.gen_bool(0.7) {
        // 70% 概率使用常见姓氏
        let idx = rng.gen_range(0..ZH_SURNAME_CHARS.len());
        ZH_SURNAME_CHARS[idx].to_string()
    } else {
        // 30% 概率生成稀有姓氏
        generate_rare_zh_surname()
    }
}

/// 生成稀有中文姓氏
fn generate_rare_zh_surname() -> String {
    let mut rng = rand::thread_rng();
    
    // 复姓概率 20%
    if rng.gen_bool(0.2) {
        // 生成复姓（如：欧阳、司马、上官等）
        let first_char = generate_surname_char();
        let second_char = generate_surname_char();
        format!("{}{}", first_char, second_char)
    } else {
        // 生成单字稀有姓氏
        generate_surname_char().to_string()
    }
}

/// 生成适合作为姓氏的汉字
fn generate_surname_char() -> char {
    let mut rng = rand::thread_rng();
    
    // 使用汉字的特定Unicode范围，倾向于选择适合姓氏的字
    let ranges = [
        (0x4E00, 0x4E99), // 一些基础汉字
        (0x5100, 0x5199), // 包含很多姓氏用字
        (0x5200, 0x5299), // 更多姓氏相关字符
    ];
    
    let range = ranges[rng.gen_range(0..ranges.len())];
    let code = rng.gen_range(range.0..=range.1);
    
    std::char::from_u32(code).unwrap_or_else(|| {
        // 如果生成失败，回退到常见姓氏
        ZH_SURNAME_CHARS[rng.gen_range(0..ZH_SURNAME_CHARS.len())]
    })
}

/// 生成中文名字
/// 根据性别和寓意智能生成
pub fn zh_cn_given_name() -> String {
    zh_cn_given_name_with_gender(None)
}

/// 根据性别生成中文名字
pub fn zh_cn_given_name_with_gender(gender: Option<Gender>) -> String {
    let mut rng = rand::thread_rng();
    let name_length = rng.gen_range(1..=2); // 1-2个字的名字
    
    let mut name = String::new();
    
    for i in 0..name_length {
        let char = if i == 0 {
            // 第一个字更注重寓意
            generate_meaningful_char(gender)
        } else {
            // 第二个字可以更灵活
            generate_complementary_char(gender)
        };
        name.push(char);
    }
    
    name
}

/// 性别枚举
#[derive(Clone, Copy)]
pub enum Gender {
    Male,
    Female,
}

/// 生成有寓意的汉字
fn generate_meaningful_char(gender: Option<Gender>) -> char {
    let mut rng = rand::thread_rng();
    
    match gender {
        Some(Gender::Female) => {
            // 女性名字倾向于柔美字符
            if rng.gen_bool(0.6) {
                ZH_GIVEN_NAME_FEMALE[rng.gen_range(0..ZH_GIVEN_NAME_FEMALE.len())]
            } else {
                ZH_GIVEN_NAME_VIRTUE[rng.gen_range(0..ZH_GIVEN_NAME_VIRTUE.len())]
            }
        },
        Some(Gender::Male) => {
            // 男性名字倾向于阳刚字符
            if rng.gen_bool(0.6) {
                ZH_GIVEN_NAME_POSITIVE[rng.gen_range(0..ZH_GIVEN_NAME_POSITIVE.len())]
            } else {
                ZH_GIVEN_NAME_VIRTUE[rng.gen_range(0..ZH_GIVEN_NAME_VIRTUE.len())]
            }
        },
        None => {
            // 随机选择类别
            let categories = [
                &ZH_GIVEN_NAME_POSITIVE,
                &ZH_GIVEN_NAME_VIRTUE,
                &ZH_GIVEN_NAME_NATURE,
                &ZH_GIVEN_NAME_FEMALE,
            ];
            let category = categories[rng.gen_range(0..categories.len())];
            category[rng.gen_range(0..category.len())]
        }
    }
}

/// 生成互补的汉字
fn generate_complementary_char(gender: Option<Gender>) -> char {
    let mut rng = rand::thread_rng();
    
    // 30% 概率使用自然相关字符，70% 概率使用其他有意义字符
    if rng.gen_bool(0.3) {
        ZH_GIVEN_NAME_NATURE[rng.gen_range(0..ZH_GIVEN_NAME_NATURE.len())]
    } else {
        generate_meaningful_char(gender)
    }
}

/// 生成英文全名
pub fn en_us_fullname() -> String {
    let given_name = en_us_given_name();
    let surname = en_us_surname();
    format!("{} {}", given_name, surname)
}

/// 生成英文姓氏
/// 使用音节组合算法生成真实感的英文姓氏
pub fn en_us_surname() -> String {
    let mut rng = rand::thread_rng();
    
    // 80% 概率生成组合姓氏，20% 概率生成简单姓氏
    if rng.gen_bool(0.8) {
        let prefix = EN_SURNAME_PREFIXES[rng.gen_range(0..EN_SURNAME_PREFIXES.len())];
        let suffix = EN_SURNAME_SUFFIXES[rng.gen_range(0..EN_SURNAME_SUFFIXES.len())];
        
        // 避免重复音节
        if prefix.to_lowercase().ends_with(&suffix.chars().next().unwrap().to_lowercase().to_string()) {
            format!("{}{}", prefix, &suffix[1..])
        } else {
            format!("{}{}", prefix, suffix)
        }
    } else {
        // 生成简单的单音节姓氏
        generate_simple_english_surname()
    }
}

/// 生成简单的英文姓氏
fn generate_simple_english_surname() -> String {
    let mut rng = rand::thread_rng();
    let consonants = ['B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'V', 'W'];
    let vowels = ['a', 'e', 'i', 'o', 'u'];
    
    let mut surname = String::new();
    
    // 辅音开头
    surname.push(consonants[rng.gen_range(0..consonants.len())]);
    
    // 添加元音
    surname.push(vowels[rng.gen_range(0..vowels.len())]);
    
    // 可能添加辅音结尾
    if rng.gen_bool(0.7) {
        surname.push(consonants[rng.gen_range(0..consonants.len())].to_lowercase().next().unwrap());
    }
    
    surname
}

/// 生成英文名字
/// 使用音节组合生成自然的英文名字
pub fn en_us_given_name() -> String {
    en_us_given_name_with_gender(None)
}

/// 根据性别生成英文名字
pub fn en_us_given_name_with_gender(gender: Option<Gender>) -> String {
    let mut rng = rand::thread_rng();
    
    // 70% 概率使用音节组合，30% 概率生成创新名字
    if rng.gen_bool(0.7) {
        let prefix = EN_GIVEN_NAME_PREFIXES[rng.gen_range(0..EN_GIVEN_NAME_PREFIXES.len())];
        let suffix = EN_GIVEN_NAME_SUFFIXES[rng.gen_range(0..EN_GIVEN_NAME_SUFFIXES.len())];
        
        let mut name = format!("{}{}", prefix, suffix);
        
        // 根据性别调整名字结尾
        match gender {
            Some(Gender::Female) => {
                if rng.gen_bool(0.4) && !name.ends_with('a') && !name.ends_with('e') {
                    name.push('a'); // 女性名字常以a结尾
                }
            },
            Some(Gender::Male) => {
                if name.ends_with('a') && rng.gen_bool(0.6) {
                    name.pop(); // 男性名字较少以a结尾
                }
            },
            None => {}
        }
        
        name
    } else {
        generate_creative_english_name(gender)
    }
}

/// 生成创新的英文名字
fn generate_creative_english_name(gender: Option<Gender>) -> String {
    let mut rng = rand::thread_rng();
    let consonants = ['B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'V', 'W', 'Z'];
    let vowels = ['a', 'e', 'i', 'o', 'u'];
    
    let mut name = String::new();
    let length = rng.gen_range(4..=8);
    
    for i in 0..length {
        if i % 2 == 0 {
            // 偶数位置放辅音
            let consonant = consonants[rng.gen_range(0..consonants.len())];
            if i == 0 {
                name.push(consonant); // 首字母大写
            } else {
                name.push(consonant.to_lowercase().next().unwrap());
            }
        } else {
            // 奇数位置放元音
            name.push(vowels[rng.gen_range(0..vowels.len())]);
        }
    }
    
    // 根据性别调整结尾
    match gender {
        Some(Gender::Female) if !name.ends_with('a') && !name.ends_with('e') && rng.gen_bool(0.5) => {
            name.push('a');
        },
        _ => {}
    }
    
    name
}

/// 生成指定长度的中文姓名
pub fn zh_cn_name_with_length(min_len: usize, max_len: usize) -> String {
    let mut rng = rand::thread_rng();
    let total_len = rng.gen_range(min_len..=max_len);
    
    let surname = zh_cn_surname();
    let surname_len = surname.chars().count();
    
    if total_len <= surname_len {
        return surname;
    }
    
    let given_name_len = total_len - surname_len;
    let mut given_name = String::new();
    
    for _ in 0..given_name_len {
        given_name.push(generate_meaningful_char(None));
    }
    
    format!("{}{}", surname, given_name)
}

/// 生成男性中文全名
pub fn zh_cn_male_fullname() -> String {
    let surname = zh_cn_surname();
    let given_name = zh_cn_given_name_with_gender(Some(Gender::Male));
    format!("{}{}", surname, given_name)
}

/// 生成女性中文全名
pub fn zh_cn_female_fullname() -> String {
    let surname = zh_cn_surname();
    let given_name = zh_cn_given_name_with_gender(Some(Gender::Female));
    format!("{}{}", surname, given_name)
}

/// 生成男性英文全名
pub fn en_us_male_fullname() -> String {
    let given_name = en_us_given_name_with_gender(Some(Gender::Male));
    let surname = en_us_surname();
    format!("{} {}", given_name, surname)
}

/// 生成女性英文全名
pub fn en_us_female_fullname() -> String {
    let given_name = en_us_given_name_with_gender(Some(Gender::Female));
    let surname = en_us_surname();
    format!("{} {}", given_name, surname)
}

/// 生成带中间名的英文全名
pub fn en_us_fullname_with_middle() -> String {
    let given_name = en_us_given_name();
    let middle_name = en_us_given_name();
    let surname = en_us_surname();
    format!("{} {} {}", given_name, middle_name, surname)
}

/// 生成英文名字缩写
pub fn en_us_initials() -> String {
    let mut rng = rand::thread_rng();
    let consonants = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    
    let first_initial = consonants[rng.gen_range(0..consonants.len())];
    let last_initial = consonants[rng.gen_range(0..consonants.len())];
    
    format!("{}.{}.", first_initial, last_initial)
}

/// 生成日文姓名（平假名）
pub fn ja_jp_fullname() -> String {
    let mut rng = rand::thread_rng();
    
    // 日文姓氏音节
    let surname_syllables = ["田", "中", "山", "木", "村", "井", "川", "原", "石", "小"];
    let surname_endings = ["田", "中", "山", "木", "村", "井", "川", "原", "石", "野"];
    
    // 日文名字音节
    let given_syllables = ["あ", "か", "さ", "た", "な", "は", "ま", "や", "ら", "わ"];
    let given_endings = ["子", "美", "恵", "香", "代", "花", "愛", "里", "奈", "菜"];
    
    let surname = format!("{}{}", 
        surname_syllables[rng.gen_range(0..surname_syllables.len())],
        surname_endings[rng.gen_range(0..surname_endings.len())]
    );
    
    let given_name = format!("{}{}", 
        given_syllables[rng.gen_range(0..given_syllables.len())],
        given_endings[rng.gen_range(0..given_endings.len())]
    );
    
    format!("{} {}", surname, given_name)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_zh_cn_fullname() {
        for _ in 0..100 {
            let name = zh_cn_fullname();
            assert!(!name.is_empty());
            assert!(name.chars().count() >= 2);
            assert!(name.chars().count() <= 4); // 最多4个字（复姓+双字名）
        }
    }

    #[test]
    fn test_zh_cn_surname_variety() {
        let mut surnames = std::collections::HashSet::new();
        for _ in 0..100 {
            surnames.insert(zh_cn_surname());
        }
        // 应该生成多样化的姓氏
        assert!(surnames.len() > 20);
    }

    #[test]
    fn test_zh_cn_gender_names() {
        let male_name = zh_cn_male_fullname();
        let female_name = zh_cn_female_fullname();
        
        assert!(!male_name.is_empty());
        assert!(!female_name.is_empty());
        assert!(male_name.chars().count() >= 2);
        assert!(female_name.chars().count() >= 2);
    }

    #[test]
    fn test_en_us_fullname() {
        for _ in 0..50 {
            let name = en_us_fullname();
            assert!(!name.is_empty());
            assert!(name.contains(' '));
            
            let parts: Vec<&str> = name.split_whitespace().collect();
            assert_eq!(parts.len(), 2); // 名 + 姓
            
            // 检查首字母大写
            assert!(parts[0].chars().next().unwrap().is_uppercase());
            assert!(parts[1].chars().next().unwrap().is_uppercase());
        }
    }

    #[test]
    fn test_en_us_surname_variety() {
        let mut surnames = std::collections::HashSet::new();
        for _ in 0..100 {
            surnames.insert(en_us_surname());
        }
        // 应该生成多样化的姓氏
        assert!(surnames.len() > 30);
    }

    #[test]
    fn test_en_us_gender_names() {
        let male_name = en_us_male_fullname();
        let female_name = en_us_female_fullname();
        
        assert!(!male_name.is_empty());
        assert!(!female_name.is_empty());
        assert!(male_name.contains(' '));
        assert!(female_name.contains(' '));
    }

    #[test]
    fn test_zh_cn_name_with_length() {
        for target_len in 2..=5 {
            let name = zh_cn_name_with_length(target_len, target_len);
            let char_count = name.chars().count();
            assert_eq!(char_count, target_len);
        }
        
        // 测试范围
        let name = zh_cn_name_with_length(2, 4);
        let char_count = name.chars().count();
        assert!(char_count >= 2 && char_count <= 4);
    }

    #[test]
    fn test_en_us_fullname_with_middle() {
        let name = en_us_fullname_with_middle();
        let parts: Vec<&str> = name.split_whitespace().collect();
        assert_eq!(parts.len(), 3); // 名 + 中间名 + 姓
    }

    #[test]
    fn test_en_us_initials() {
        let initials = en_us_initials();
        assert_eq!(initials.len(), 4); // "A.B." 格式
        assert!(initials.contains('.'));
        assert_eq!(initials.chars().filter(|&c| c == '.').count(), 2);
    }

    #[test]
    fn test_ja_jp_fullname() {
        let name = ja_jp_fullname();
        assert!(!name.is_empty());
        assert!(name.contains(' '));
        
        let parts: Vec<&str> = name.split_whitespace().collect();
        assert_eq!(parts.len(), 2);
    }

    #[test]
    fn test_name_generation_performance() {
        use std::time::Instant;
        
        let start = Instant::now();
        for _ in 0..1000 {
            zh_cn_fullname();
            en_us_fullname();
        }
        let duration = start.elapsed();
        
        // 应该能在合理时间内完成
        assert!(duration.as_millis() < 1000);
    }

    #[test]
    fn test_name_uniqueness() {
        let mut zh_names = std::collections::HashSet::new();
        let mut en_names = std::collections::HashSet::new();
        
        for _ in 0..200 {
            zh_names.insert(zh_cn_fullname());
            en_names.insert(en_us_fullname());
        }
        
        // 大部分名字应该是唯一的
        assert!(zh_names.len() > 150);
        assert!(en_names.len() > 150);
    }
}